package com.taiyi.renaissancemall.ui.mine;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.taiyi.renaissancemall.R;
import com.taiyi.renaissancemall.Utils.ToastUtils;
import com.taiyi.renaissancemall.Utils.Utils;
import com.taiyi.renaissancemall.adapter.AdapterManager;
import com.taiyi.renaissancemall.adapter.baseadapter.CommonAdapter;
import com.taiyi.renaissancemall.adapter.baseadapter.MultiItemTypeAdapter;
import com.taiyi.renaissancemall.base.BaseFragment;
import com.taiyi.renaissancemall.base.MyApp;
import com.taiyi.renaissancemall.bean.MenuBean;
import com.taiyi.renaissancemall.bean.PersonInfoBean;
import com.taiyi.renaissancemall.bean.VerifiedBean;
import com.taiyi.renaissancemall.bean.VersionUpdateBean;
import com.taiyi.renaissancemall.ui.login.LoginActivity;
import com.taiyi.renaissancemall.ui.main.first.memberBenefits.MemberBenefitsActivity;
import com.taiyi.renaissancemall.ui.main.personshare.PersonShareActivity;
import com.taiyi.renaissancemall.ui.mine.address.ShippingAddressActivity;
import com.taiyi.renaissancemall.ui.mine.aftersale.AfterSalesActivity;
import com.taiyi.renaissancemall.ui.mine.collect.MyCollect2Activity;
import com.taiyi.renaissancemall.ui.mine.order.MyOrderActivity;
import com.taiyi.renaissancemall.ui.mine.scores.MyScoresActivity;
import com.taiyi.renaissancemall.ui.mine.team.MyTeamActivity;
import com.taiyi.renaissancemall.ui.mine.updateUser.UpdateUserActivity;
import com.taiyi.renaissancemall.ui.mine.verified.VerifiedActivity;
import com.taiyi.renaissancemall.ui.mine.wallet.MyWalletActivity;
import com.taiyi.renaissancemall.ui.mine.withdraw.WithdrawSettingActivity;
import com.taiyi.renaissancemall.ui.webview.WebViewActivity;

import java.text.DecimalFormat;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.view.View.VISIBLE;

public class MineFragment extends BaseFragment<MineFragmentView, MineFragmentPresent> implements MineFragmentView {
    @BindView(R.id.rightTitleTv)
    TextView rightTitleTv;
    @BindView(R.id.topB)
    TextView topB;
    @BindView(R.id.avatarIv)
    ImageView avatarIv;
    @BindView(R.id.rect)
    TextView rect;
    @BindView(R.id.myOrder)
    TextView myOrder;
    @BindView(R.id.dfkTv)
    TextView dfkTv;
    @BindView(R.id.dfhTv)
    TextView dfhTv;
    @BindView(R.id.dshTv)
    TextView dshTv;
    @BindView(R.id.dpjTv)
    TextView dpjTv;
    @BindView(R.id.shTv)
    TextView shTv;
    @BindView(R.id.wallet)
    TextView wallet;
    @BindView(R.id.myWallet)
    TextView myWallet;
    @BindView(R.id.textView3)
    TextView textView3;
    @BindView(R.id.textView4)
    TextView textView4;
    @BindView(R.id.textView5)
    TextView textView5;
    @BindView(R.id.textView6)
    TextView textView6;
    @BindView(R.id.textView7)
    TextView textView7;
    @BindView(R.id.textView8)
    TextView textView8;
    @BindView(R.id.v)
    View v;
    @BindView(R.id.signOutTv)
    TextView signOutTv;
    @BindView(R.id.iv_person_lv)
    ImageView ivPersonLv;
    @BindView(R.id.tv_mine_small_level)
    TextView tvMineSmallLevel;
    private List<String> titleList = new LinkedList<>();
    private List<Integer> resList = new LinkedList<>();
    private List<MenuBean> menuBeanList = new LinkedList<>();
    private List<String> list = new LinkedList<>();
    private List<MenuBean> mList = new LinkedList<>();
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.recyclerViewR)
    RecyclerView recyclerViewR;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.nameTv)
    TextView nameTv;
    @BindView(R.id.backIv)
    ImageView backIv;
    @BindView(R.id.rightIv)
    ImageView rightIv;

    @BindView(R.id.top)
    ConstraintLayout top;
    private String scores;
    private String ifSign;
    private String status_verified;
    private String tel;

    @Override
    public MineFragmentPresent initPresenter() {
        return new MineFragmentPresent();
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        backIv.setVisibility(View.GONE);
        titleTv.setText(getString(R.string.personalCenter));
        initVersionUpdateDialog();
        Collections.addAll(titleList, getString(R.string.myCollection), getString(R.string.myTeam)
                , getString(R.string.equityMap), getString(R.string.verified)
                , getString(R.string.browsingHistory), getString(R.string.shippingAddress)
                , getString(R.string.personalPoster), getString(R.string.businessSchool)
                , getString(R.string.coupon), getString(R.string.myScores));
        Collections.addAll(resList, R.mipmap.mine_collection_iv, R.mipmap.mine_team_iv
                , R.mipmap.mine_map_iv, R.mipmap.mine_verifical_iv
                , R.mipmap.mine_history_iv, R.mipmap.mine_address_iv
                , R.mipmap.mine_poster_iv, R.mipmap.mine_school_iv
                , R.mipmap.mine_coupon_iv, R.mipmap.mine_scores_iv);
        Collections.addAll(list, getString(R.string.withdrawalSettings), getString(R.string.customerService)
                , getString(R.string.commonProblem), getString(R.string.aboutUs)
                , getString(R.string.feedBack), getString(R.string.setCenter), getString(R.string.currentVersion));
        for (int i = 0; i < titleList.size(); i++) {
            MenuBean menuBean = new MenuBean(titleList.get(i), resList.get(i));
            menuBeanList.add(menuBean);
        }
        for (int i = 0; i < list.size(); i++) {
            MenuBean menuBean = new MenuBean(list.get(i), 1);
            mList.add(menuBean);
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(MyApp.getInstance(), 5);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
        CommonAdapter mineFunctionalListAdapter = AdapterManager.getMineFunctionalListAdapter(MyApp.getInstance(), menuBeanList);
        recyclerView.setAdapter(mineFunctionalListAdapter);
        mineFunctionalListAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (position == 0) {
                    //我的收藏
                    Intent intent = new Intent(getActivity(), MyCollect2Activity.class);
                    intent.putExtra("com_type", "1");
                    startActivity(intent);
                } else if (position == 1) {
                    //我的团队
                    Intent intent = new Intent(getActivity(), MyTeamActivity.class);
                    startActivity(intent);
                } else if (position == 2) {
                    //权益地图
                    ToastUtils.showLongToast(R.string.notOpenYet);
                } else if (position == 3) {
                    //实名认证
                    if (status_verified != null && !TextUtils.isEmpty(status_verified)) {
                        //-1未实名 0.认证未通过 1.认证中 2.认证通过

                        if ("0".equals(status_verified)) {
                            Intent intent = new Intent(getActivity(), VerifiedActivity.class);
                            intent.putExtra("isThrough", 1);
                            startActivity(intent);
                        } else if ("-1".equals(status_verified)) {
                            Intent intent = new Intent(getActivity(), VerifiedActivity.class);
                            intent.putExtra("isThrough", 0);
                            startActivity(intent);
                        } else if ("1".equals(status_verified)) {
                            ToastUtils.showShortToast("正在审核中");
                        } else if ("2".equals(status_verified)) {
                            ToastUtils.showShortToast("该用户实名认证已通过");
                        }
//
//                        Intent intent = new Intent(getActivity(), VerifiedActivity.class);
//                        intent.putExtra("isThrough", status_verified);
//                        startActivity(intent);
                    }
                } else if (position == 4) {
                    //浏览记录
                    Intent intent = new Intent(getActivity(), MyCollect2Activity.class);
                    intent.putExtra("com_type", "2");
                    startActivity(intent);
                } else if (position == 5) {
                    //收货地址
                    Intent intent = new Intent(getActivity(), ShippingAddressActivity.class);
                    startActivity(intent);
                } else if (position == 6) {
                    //个人海报
                    startActivity(new Intent(getContext(), PersonShareActivity.class));
                } else if (position == 7) {
                    //商学院
                    ToastUtils.showShortToast(R.string.notOpenYet);
                } else if (position == 8) {
                    //优惠券
                    ToastUtils.showShortToast(R.string.notOpenYet);
                } else if (position == 9) {
                    //我的积分
                    Intent intent = new Intent(getActivity(), MyScoresActivity.class);
                    intent.putExtra("scorenum", scores);
                    startActivity(intent);
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setSmoothScrollbarEnabled(true);
        linearLayoutManager.setAutoMeasureEnabled(true);
        recyclerViewR.setLayoutManager(linearLayoutManager);

        recyclerViewR.setHasFixedSize(true);
        recyclerViewR.setNestedScrollingEnabled(false);
        CommonAdapter mineMenuListAdapter = AdapterManager.getMineMenuListAdapter(MyApp.getInstance(), mList);
        recyclerViewR.setAdapter(mineMenuListAdapter);
        mineMenuListAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (position == 0) {
                    //提现设置
                    Intent intent = new Intent(getActivity(), WithdrawSettingActivity.class);
                    intent.putExtra("whereCode", 1);
                    intent.putExtra("tel", tel);
                    startActivity(intent);
                } else if (position == 1) {
                    //专属客服
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_DIAL);
                    Uri uri = Uri.parse("tel:" + "4000011721");
                    intent.setData(uri);
                    startActivity(intent);
                } else if (position == 2) {
                    //常见问题
                    Intent intent = new Intent(getActivity(), WebViewActivity.class);
                    intent.putExtra("isWhere", 2);
                    startActivity(intent);
                } else if (position == 3) {
                    //关于我们
                    Intent intent = new Intent(getActivity(), WebViewActivity.class);
                    intent.putExtra("isWhere", 3);
                    startActivity(intent);
                } else if (position == 4) {
                    //意见反馈
                    ToastUtils.showShortToast(R.string.notOpenYet);
                } else if (position == 5) {
                    //设置中心
                    ToastUtils.showShortToast(R.string.notOpenYet);
                } else if (position == 6) {
                    //版本更新
                    showProgress();
                    presenter.checkVersionUpdate();
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    private Dialog updateDialog;
    private TextView contentTv, forceUpdateTv, laterTv, updateTv;
    private VersionUpdateBean myVersionUpdateBean;

    private void initVersionUpdateDialog() {
        updateDialog = new Dialog(getContext(), R.style.MyDialog);
        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.version_update_dialog_layout, null);
        updateDialog.setContentView(inflate);
        updateDialog.setCanceledOnTouchOutside(false);
        updateDialog.setCancelable(false);
        contentTv = inflate.findViewById(R.id.contentTv);
        forceUpdateTv = inflate.findViewById(R.id.forceUpdateTv);
        laterTv = inflate.findViewById(R.id.laterTv);
        updateTv = inflate.findViewById(R.id.updateTv);
        forceUpdateTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String downUrl = myVersionUpdateBean.getDownUrl();
                openBrowser(getContext(), downUrl);
            }
        });
        laterTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
            }
        });
        updateTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String downUrl = myVersionUpdateBean.getDownUrl();
                openBrowser(getContext(), downUrl);
            }
        });

    }

    private void openBrowser(Context context, String url) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
        // 官方解释 : Name of the component implementing an activity that can display the intent
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            // 打印Log   ComponentName到底是什么
            context.startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {
            toast("未找到手机中的浏览器");
        }
    }

    @OnClick({R.id.dfkTv, R.id.dfhTv, R.id.dshTv, R.id.signOutTv, R.id.dpjTv, R.id.shTv})
    public void onClick(View view) {
        Intent intent = new Intent(getActivity(), MyOrderActivity.class);
        switch (view.getId()) {
            case R.id.dfkTv:
                intent.putExtra("type", 0);
                startActivity(intent);
                break;
            case R.id.dfhTv:
                intent.putExtra("type", 1);
                startActivity(intent);
                break;
            case R.id.dshTv:
                intent.putExtra("type", 2);
                startActivity(intent);
                break;
            case R.id.dpjTv:
                intent.putExtra("type", 3);
                startActivity(intent);
                break;
            case R.id.shTv:
                startActivity(new Intent(getContext(), AfterSalesActivity.class));
                break;
            case R.id.signOutTv:
                Utils.getSpUtils().remove("token");
                startActivity(new Intent(getContext(), LoginActivity.class));
                getActivity().finish();
                break;
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        presenter.getPersonInfo();
    }

    @Override
    protected void initData() {
        presenter.getPersonInfo();
    }

    @Override
    public void initEvent() {

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.mine_fragment_layout;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(top).init();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            mImmersionBar.titleBar(top).init();
        }
    }

    @Override
    public void getPersonInfoSuccess(PersonInfoBean personInfoBean) {
hideProgress();
        tel = personInfoBean.getTel();
        status_verified = personInfoBean.getStatus();
        tvMineSmallLevel.setText(personInfoBean.getRongname());

        if (personInfoBean.getRongname() != null && !"".equals(personInfoBean.getRongname())) {
            if ("一星铂金".equals(personInfoBean.getRongname())) {
                ivPersonLv.setImageResource(R.mipmap.yixingbaijin);
            } else if ("二星铂金".equals(personInfoBean.getRongname())) {
                ivPersonLv.setImageResource(R.mipmap.erxingbaijin);
            } else if ("三星铂金".equals(personInfoBean.getRongname())) {
                ivPersonLv.setImageResource(R.mipmap.sanxingbaijin);
            } else if ("四星铂金".equals(personInfoBean.getRongname())) {
                ivPersonLv.setImageResource(R.mipmap.sixingbaijin);
            } else if ("五星铂金".equals(personInfoBean.getRongname())) {
                ivPersonLv.setImageResource(R.mipmap.wuxingbaijin);
            } else if ("钻石".equals(personInfoBean.getRongname())) {
                ivPersonLv.setImageResource(R.mipmap.zuanshihuiyuan);
            }
        } else {
            if (personInfoBean.getLevelid() == 1) {
                ivPersonLv.setImageResource(R.mipmap.putonghuiyuan);
            } else if (personInfoBean.getLevelid() == 2) {
                ivPersonLv.setImageResource(R.mipmap.jinkahuiyuan);
            } else if (personInfoBean.getLevelid() == 3) {
                ivPersonLv.setImageResource(R.mipmap.baijinhuiyuan);
            } else if (personInfoBean.getLevelid() == 4) {
                ivPersonLv.setImageResource(R.mipmap.zuanshihuiyuan);
            }
        }

        String userLv = personInfoBean.getLevelname() + "会员";
        textView5.setText(userLv);
        textView6.setText(personInfoBean.getDaoqistr());
        String bvNum = personInfoBean.getBvnum() + "BV";
        textView7.setText(bvNum);
        textView8.setText(personInfoBean.getShengjistr());

        //"ifdrqian": "2今日无签到1已签到"
        ifSign = personInfoBean.getIfdrqian();
        if ("1".equals(ifSign)) {
            rightIv.setImageResource(R.mipmap.personal_signin_btn);
        } else if ("2".equals(ifSign)) {
            rightIv.setImageResource(R.mipmap.personal_signout_btn);
        }

        if ("".equals(personInfoBean.getRealname()) || personInfoBean.getRealname() == null) {
            nameTv.setText(personInfoBean.getTel());
        } else {
            nameTv.setText(personInfoBean.getRealname());
        }

        String numLock;
        if (personInfoBean.getLiquannumlock().contains(".0")) {
            double daiMoney = Double.parseDouble(personInfoBean.getLiquannumlock());
            String daiMoneyFormat = new DecimalFormat("#").format(daiMoney);
            numLock = getString(R.string.preSettlementGiftCertificate) + daiMoneyFormat;
        } else {
            numLock = getString(R.string.preSettlementGiftCertificate) + personInfoBean.getLiquannumlock();
        }
        String numTi;
        if (personInfoBean.getLiquannumti().contains(".0")) {
            double daiMoney = Double.parseDouble(personInfoBean.getLiquannumti());
            String daiMoneyFormat = new DecimalFormat("#").format(daiMoney);
            numTi = getString(R.string.withDrawable) + daiMoneyFormat;
        } else {
            numTi = getString(R.string.withDrawable) + personInfoBean.getLiquannumti();
        }
        scores = personInfoBean.getScorenum();

        textView3.setText(numLock);
        textView4.setText(numTi);

        if (personInfoBean.getHeadimg() != null && !"".equals(personInfoBean.getHeadimg())) {
            Glide.with(this).load(personInfoBean.getHeadimg()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(avatarIv);
        }
    }

    @Override
    public void getPersonInfoFailure(String msg) {
        toast(msg);
    }

    @Override
    public void toSignSuccess(VerifiedBean verifiedBean) {
        hideProgress();
        ToastUtils.showShortToast("签到成功");
        ifSign = "1";
        rightIv.setImageResource(R.mipmap.personal_signin_btn);
    }

    @Override
    public void toSignFailure(String msg) {
        hideProgress();
        toast(msg);
        ifSign = "2";
        rightIv.setImageResource(R.mipmap.personal_signout_btn);
    }

    @Override
    public void getVersionSuccess(VersionUpdateBean versionUpdateBean) {
        hideProgress();
        myVersionUpdateBean = versionUpdateBean;
        long appVersionCode = presenter.getAppVersionCode();
        long newVersionCode = Long.parseLong(versionUpdateBean.getVersionUp());

        if (newVersionCode > appVersionCode) {
            contentTv.setText(versionUpdateBean.getIntroduce());
            String force = versionUpdateBean.getIsForce();//0不是强制更新  1强制更新
            if ("0".equals(force)) {
                laterTv.setVisibility(VISIBLE);
                updateTv.setVisibility(VISIBLE);
            } else {

                forceUpdateTv.setVisibility(VISIBLE);
            }
            updateDialog.show();
        } else {
            ToastUtils.showShortToast("当前已是最新版本");
        }


    }

    @Override
    public void getVersionFailure(String msg) {
        hideProgress();
        toast(msg);
    }

    @OnClick({R.id.wallet, R.id.avatarIv, R.id.rightIv})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.wallet) {
            Intent intent = new Intent(getActivity(), MyWalletActivity.class);
            startActivity(intent);
        } else if (view.getId() == R.id.avatarIv) {
            Intent intent = new Intent(getActivity(), UpdateUserActivity.class);
            startActivity(intent);
        } else if (view.getId() == R.id.rightIv) {
            if ("1".equals(ifSign)) {
                ToastUtils.showLongToast("今日已签到");
            } else if ("2".equals(ifSign)) {
                //1补签2今日签到
                showProgress();
                presenter.toSign("2");
            }
        }
    }
}
